<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文档智能系统</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-color: #2563eb;
            --primary-hover: #1d4ed8;
            --success-color: #10b981;
            --success-hover: #059669;
            --danger-color: #ef4444;
            --danger-hover: #dc2626;
            --background-color: #f8fafc;
            --card-background: #ffffff;
            --text-primary: #1e293b;
            --text-secondary: #64748b;
            --border-color: #e2e8f0;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background-color: var(--background-color);
            color: var(--text-primary);
            line-height: 1.5;
            padding: 2rem;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            margin-bottom: 2rem;
            padding: 2rem;
            background-color: var(--card-background);
            border-radius: 1rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .header h1 {
            font-size: 2rem;
            color: var(--text-primary);
            margin-bottom: 0.5rem;
        }

        .header p {
            color: var(--text-secondary);
            font-size: 1rem; /* 调整字体大小 */
            margin-bottom: 1.5rem; /* 增加与下方元素的间距 */
        }

        .header-features {
            display: flex;
            justify-content: center;
            gap: 1rem; /* 减小特性之间的间距 */
            margin-top: 1rem; /* 减小与上方元素的间距 */
        }

        .feature-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 0.25rem; /* 减小图标和文字之间的间距 */
            padding: 0.75rem; /* 减小内边距 */
            background-color: var(--background-color);
            border-radius: 0.5rem; /* 减小圆角 */
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            transition: transform 0.2s ease, box-shadow 0.2s ease;
            min-width: 100px; /* 减小最小宽度 */
        }

        .feature-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }

        .feature-icon {
            font-size: 1.5rem; /* 减小图标大小 */
            color: var(--primary-color);
            margin-bottom: 0.25rem; /* 减小图标和文字的间距 */
        }

        .feature-text {
            font-size: 0.75rem; /* 减小文字大小 */
            color: var(--text-primary);
            font-weight: 500;
        }

        .section {
            background-color: var(--card-background);
            border-radius: 1rem;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .section h2 {
            font-size: 1.25rem;
            color: var(--text-primary);
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid var(--border-color);
        }

        .button {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border-radius: 0.25rem;
            cursor: pointer;
            transition: all 0.2s;
            border: none;
            font-size: 0.875rem;
            min-width: 100px;
            justify-content: center;
        }

        .button-primary {
            background-color: var(--primary-color);
            color: white;
        }

        .button-primary:hover {
            background-color: var(--primary-hover);
        }

        .button-success {
            background-color: var(--success-color);
            color: white;
        }

        .button-success:hover {
            background-color: var(--success-hover);
        }

        .button-danger {
            background-color: var(--danger-color);
            color: white;
        }

        .button-danger:hover {
            background-color: var(--danger-hover);
        }

        .button-secondary {
            background-color: var(--secondary-color);
            color: white;
        }

        .button-secondary:hover {
            background-color: var(--secondary-hover-color);
        }

        .button .icon {
            font-size: 1rem;
        }

        .file-upload {
            display: flex;
            flex-direction: column;
            gap: 1rem;
            margin-bottom: 1.5rem;
            background-color: var(--card-background);
            border-radius: 1rem;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .file-input-container {
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 2rem;
            border: 2px dashed var(--border-color);
            border-radius: 0.75rem;
            background-color: var(--background-color);
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .file-input-container:hover {
            border-color: var(--primary-color);
            background-color: rgba(37, 99, 235, 0.05);
        }

        .file-input-container.dragover {
            border-color: var(--primary-color);
            background-color: rgba(37, 99, 235, 0.1);
        }

        .file-input {
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            opacity: 0;
            cursor: pointer;
        }

        .upload-icon {
            font-size: 2.5rem;
            color: var(--primary-color);
            margin-bottom: 1rem;
        }

        .upload-text {
            text-align: center;
            color: var(--text-secondary);
        }

        .upload-text h3 {
            font-size: 1.25rem;
            margin-bottom: 0.5rem;
            color: var(--text-primary);
        }

        .upload-text p {
            font-size: 0.875rem;
            margin: 0;
        }

        .upload-actions {
            display: flex;
            justify-content: center;
            gap: 1rem;
            margin-top: 1rem;
        }

        .button {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1.5rem;
            border-radius: 0.5rem;
            font-weight: 500;
            transition: all 0.2s ease;
            border: none;
            cursor: pointer;
            font-size: 0.875rem;
            min-width: 120px;
            justify-content: center;
        }

        .button-primary {
            background-color: var(--primary-color);
            color: white;
        }

        .button-primary:hover {
            background-color: var(--primary-hover);
            transform: translateY(-1px);
        }

        .button-primary:disabled {
            background-color: var(--border-color);
            cursor: not-allowed;
            transform: none;
        }

        .button-secondary {
            background-color: var(--background-color);
            color: var(--text-primary);
            border: 1px solid var(--border-color);
        }

        .button-secondary:hover {
            background-color: var(--border-color);
            transform: translateY(-1px);
        }

        .file-info {
            display: none;
            align-items: center;
            gap: 1rem;
            padding: 1rem;
            background-color: var(--background-color);
            border-radius: 0.5rem;
            margin-top: 1rem;
        }

        .file-info.active {
            display: flex;
        }

        .file-icon {
            font-size: 1.5rem;
            color: var(--primary-color);
        }

        .file-details {
            flex: 1;
        }

        .file-name {
            font-weight: 500;
            color: var(--text-primary);
            margin-bottom: 0.25rem;
        }

        .file-size {
            font-size: 0.875rem;
            color: var(--text-secondary);
        }

        .file-remove {
            color: var(--danger-color);
            cursor: pointer;
            padding: 0.5rem;
            border-radius: 0.25rem;
            transition: all 0.2s ease;
        }

        .file-remove:hover {
            background-color: rgba(239, 68, 68, 0.1);
        }

        .file-list {
            margin-top: 1rem;
        }

        .file-item {
            display: flex;
            align-items: center;
            padding: 1rem;
            background-color: var(--background-color);
            border-radius: 0.5rem;
            margin-bottom: 0.5rem;
            transition: all 0.2s;
            gap: 1rem;
        }

        .file-name {
            flex: 1;
            color: var(--text-primary);
            cursor: pointer;
            font-weight: 500;
            word-break: break-all;
            padding: 0.5rem 0;
            transition: color 0.2s;
        }

        .file-name:hover {
            color: var(--primary-color);
        }

        .file-actions {
            display: flex;
            justify-content: center;
            gap: 1rem;
        }

        .file-actions .button {
            padding: 0.5rem 1rem;
            font-size: 0.875rem;
            border-radius: 0.375rem;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            min-width: auto;
            text-decoration: none;
        }

        .file-actions .button-primary {
            background-color: var(--primary-color);
            color: white;
        }

        .file-actions .button-primary:hover {
            background-color: var(--primary-hover);
            transform: translateY(-1px);
        }

        .file-actions .button:not(.button-primary) {
            background-color: var(--background-color);
            color: var(--text-primary);
            border: 1px solid var(--border-color);
        }

        .file-actions .button:not(.button-primary):hover {
            background-color: var(--border-color);
            transform: translateY(-1px);
        }

        .file-item:hover {
            background-color: #f1f5f9;
            transform: translateX(4px);
        }

        .status {
            background-color: #1e1e1e;
            color: #d4d4d4;
            font-family: 'Consolas', 'Monaco', monospace;
            padding: 0;
            margin: 0;
            line-height: 24px;
            font-size: 13px;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        .status.error {
            color: #f48771;
        }

        .status.success {
            color: #6a9955;
        }

        #convertStatus {
            max-height: none;  /* 移除最大高度限制 */
            overflow-y: visible;  /* 移除滚动条 */
            background-color: #1e1e1e;
            border-radius: 4px;
            padding: 8px;
            margin-top: 10px;
            transition: all 0.3s ease;
        }

        #convertStatus.expanded {
            max-height: none;  /* 展开状态也不需要最大高度限制 */
        }

        .status-toggle {
            position: absolute;
            right: 8px;
            top: 8px;
            background: none;
            border: none;
            color: #d4d4d4;
            cursor: pointer;
            font-size: 12px;
            padding: 2px 6px;
            border-radius: 3px;
        }

        .status-toggle:hover {
            background-color: #424242;
        }

        .status-container {
            position: relative;
        }

        #convertStatus::-webkit-scrollbar {
            width: 8px;
        }

        #convertStatus::-webkit-scrollbar-track {
            background: #1e1e1e;
        }

        #convertStatus::-webkit-scrollbar-thumb {
            background: #424242;
            border-radius: 4px;
        }

        #convertStatus::-webkit-scrollbar-thumb:hover {
            background: #4f4f4f;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }

        .modal-content {
            background-color: var(--card-background);
            margin: 5% auto;
            padding: 2rem;
            width: 90%;
            max-width: 1000px;
            height: 80vh;
            border-radius: 1rem;
            position: relative;
            display: flex;
            flex-direction: column;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid var(--border-color);
        }

        .modal-body {
            flex: 1;
            overflow-y: auto;
            padding: 1rem;
            background-color: var(--background-color);
            border-radius: 0.5rem;
        }

        .close {
            font-size: 1.5rem;
            color: var(--text-secondary);
            cursor: pointer;
            transition: color 0.2s;
        }

        .close:hover {
            color: var(--danger-color);
        }

        /* QA 列表样式 */
        .qa-list {
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .qa-item {
            background-color: var(--card-background);
            padding: 1rem;
            border-radius: 0.5rem;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
        }

        .qa-question {
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 0.5rem;
        }

        .qa-answer {
            color: var(--text-secondary);
            margin-left: 1rem;
        }

        /* 配置部分样式 */
        .config-section {
            background-color: var(--background-color);
            padding: 1.5rem;
            border-radius: 0.5rem;
            margin-top: 1.5rem;
        }

        .config-input {
            width: 100%;
            padding: 0.75rem;
            margin: 0.5rem 0;
            border: 1px solid var(--border-color);
            border-radius: 0.5rem;
            background-color: var(--card-background);
            transition: border-color 0.2s;
        }

        .config-input:focus {
            outline: none;
            border-color: var(--primary-color);
        }

        .config-label {
            display: block;
            margin-top: 1rem;
            font-weight: 500;
            color: var(--text-primary);
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            body {
                padding: 1rem;
            }

            .file-actions {
                flex-direction: column;
            }

            .modal-content {
                width: 95%;
                margin: 10% auto;
            }
        }

        .footer {
            margin-top: 3rem;
            padding: 1.5rem;
            text-align: center;
            background-color: var(--card-background);
            border-radius: 1rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .footer-content {
            color: var(--text-secondary);
            font-size: 0.875rem;
            display: flex;
            justify-content: center;
            gap: 1rem;
        }

        .footer-content a {
            text-decoration: none;
        }

        .main-container {
            display: flex;
            gap: 2rem;
        }

        .left-panel {
            flex: 1;
            min-width: 0; /* 防止flex子项溢出 */
        }

        .right-panel {
            width: 500px;
            background-color: var(--card-background);
            border-radius: 1rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            padding: 1.5rem;
            display: none; /* 默认隐藏 */
            position: relative; /* 为关闭按钮定位 */
        }

        .right-panel.active {
            display: block;
        }

        .panel-close {
            position: absolute;
            top: 1rem;
            right: 1rem;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: var(--background-color);
            border: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s;
        }

        .panel-close:hover {
            background-color: var(--danger-color);
            border-color: var(--danger-color);
            color: white;
        }

        .panel-close::before,
        .panel-close::after {
            content: '';
            position: absolute;
            width: 16px;
            height: 2px;
            background-color: currentColor;
            border-radius: 1px;
        }

        .panel-close::before {
            transform: rotate(45deg);
        }

        .panel-close::after {
            transform: rotate(-45deg);
        }

        .prompt-section {
            margin-bottom: 1.5rem;
        }

        .prompt-textarea {
            width: 100%;
            height: 150px;
            padding: 1rem;
            border: 1px solid var(--border-color);
            border-radius: 0.5rem;
            background-color: var(--background-color);
            font-family: 'Inter', sans-serif;
            font-size: 0.875rem;
            resize: vertical;
            margin-bottom: 1rem;
        }

        .prompt-textarea:focus {
            outline: none;
            border-color: var(--primary-color);
        }

        .qa-preview-section {
            flex: 1;
            overflow-y: auto;
            max-height: calc(100vh - 400px);
            padding: 1rem;
            background-color: var(--background-color);
            border-radius: 0.5rem;
        }

        .qa-item {
            background-color: var(--card-background);
            padding: 1rem;
            border-radius: 0.5rem;
            margin-bottom: 1rem;
        }

        .qa-content {
            white-space: pre-wrap;
            word-wrap: break-word;
            font-family: 'Inter', sans-serif;
            line-height: 1.6;
            color: var(--text-primary);
        }

        .qa-preview-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid var(--border-color);
        }

        .qa-preview-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: var(--text-primary);
        }

        .qa-preview-count {
            color: var(--text-secondary);
            font-size: 0.875rem;
        }

        .qa-actions {
            display: flex;
            gap: 0.5rem;
            margin-top: 1rem;
        }

        .config-section {
            margin-top: 1.5rem;
            padding-top: 1.5rem;
            border-top: 2px solid var(--border-color);
        }

        @media (max-width: 1200px) {
            .main-container {
                flex-direction: column;
            }

            .right-panel {
                width: 100%;
            }
        }

        .extraction-controls {
            display: flex;
            flex-direction: column;
            gap: 1rem;
            margin-top: 1rem;
        }

        .progress-container {
            width: 100%;
        }

        .progress-bar {
            width: 100%;
            height: 8px;
            background-color: var(--border-color);
            border-radius: 4px;
            overflow: hidden;
        }

        .progress-fill {
            width: 0%;
            height: 100%;
            background-color: var(--primary-color);
            transition: width 0.3s ease;
        }

        .progress-status {
            margin-top: 0.5rem;
            font-size: 0.875rem;
            color: var(--text-secondary);
            text-align: center;
        }

        .button:disabled {
            opacity: 0.7;
            cursor: not-allowed;
        }

        @keyframes progress-animation {
            0% { width: 0%; }
            100% { width: 100%; }
        }

        .progress-fill.animate {
            animation: progress-animation 2s ease-in-out infinite;
        }

        .panel-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid var(--border-color);
        }

        .panel-actions {
            display: flex;
            gap: 1rem;
            align-items: center;
        }

        .button-secondary {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            background-color: var(--text-secondary);
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 0.25rem;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .button-secondary:hover {
            background-color: var(--text-primary);
        }

        .button-secondary .icon {
            font-size: 1rem;
        }

        .settings-modal {
            max-width: 600px;
            height: auto;
        }

        .settings-section {
            padding: 1rem;
        }

        .settings-actions {
            padding: 1rem;
            border-top: 2px solid var(--border-color);
            display: flex;
            justify-content: flex-end;
        }

        .button {
            white-space: nowrap;
        }

        /* 确保进度条容器可见 */
        .progress-container {
            margin-top: 1rem;
        }

        /* 添加文件名显示样式 */
        .current-file {
            font-size: 0.875rem;
            color: var(--text-secondary);
            margin-bottom: 1rem;
            padding: 0.5rem;
            background-color: var(--background-color);
            border-radius: 0.5rem;
            word-break: break-all;
        }

        .status-messages {
            margin-top: 1rem;
            max-height: 200px;
            overflow-y: auto;
        }

        .progress-message {
            padding: 0.5rem;
            margin: 0.5rem 0;
            border-radius: 0.25rem;
            font-size: 0.875rem;
        }

        .success-message {
            background-color: var(--success-color);
            color: white;
        }

        .error-message {
            background-color: var(--danger-color);
            color: white;
        }

        #qaPreviewList {
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        /* 修改 QA 预览面板的样式 */
        .qa-preview-container {
            position: relative;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            background: #fff;
            margin-bottom: 20px;
        }

        .qa-preview-content {
            max-height: 200px;
            overflow-y: auto;
            padding: 15px;
            transition: max-height 0.3s ease;
        }

        .qa-preview-content .qa-content {
            white-space: pre-wrap;
            font-family: monospace;
            line-height: 1.5;
            color: #333;
        }

        .qa-preview-expand {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 40px;
            background: linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 50%);
            display: flex;
            justify-content: center;
            align-items: center;
            border-top: 1px solid #e0e0e0;
        }

        .expand-button {
            background: #fff;
            border: 1px solid #e0e0e0;
            border-radius: 20px;
            padding: 5px 15px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 14px;
            color: #666;
            transition: all 0.2s ease;
        }

        .expand-button:hover {
            background: #f5f5f5;
            border-color: #ccc;
        }

        .expand-icon {
            font-size: 12px;
            transition: transform 0.3s ease;
        }

        /* 展开状态的样式 */
        .qa-preview-container.expanded .qa-preview-content {
            max-height: none;
        }

        .qa-preview-container.expanded .qa-preview-expand {
            position: relative;
            background: none;
            border-top: 1px solid #e0e0e0;
        }

        /* 滚动条样式 */
        .qa-preview-content::-webkit-scrollbar {
            width: 8px;
        }

        .qa-preview-content::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }

        .qa-preview-content::-webkit-scrollbar-thumb {
            background: #ccc;
            border-radius: 4px;
        }

        .qa-preview-content::-webkit-scrollbar-thumb:hover {
            background: #999;
        }

        .file-actions a.button {
            text-decoration: none;
        }

        .current-file-display {
            background-color: var(--background-color);
            padding: 0.75rem 1rem;
            border-radius: 0.5rem;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .current-file-label {
            color: var(--text-secondary);
            font-size: 0.875rem;
        }

        .current-file-name {
            color: var(--text-primary);
            font-weight: 500;
            font-size: 0.875rem;
        }

        /* 添加悬浮设置按钮样式 */
        .floating-settings {
            position: fixed;
            bottom: 2rem;
            right: 2rem;
            min-width: 45px;
            height: 45px;
            background-color: var(--card-background);
            border-radius: 23px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            z-index: 1000;
            border: 1px solid var(--border-color);
            padding: 0 16px;
        }

        .floating-settings:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
            background-color: var(--background-color);
        }

        .floating-settings .text {
            color: var(--text-secondary);
            font-size: 14px;
            transition: color 0.2s ease;
            white-space: nowrap;
        }

        .floating-settings:hover .text {
            color: var(--text-primary);
        }

        /* 系统设置模态框样式 */
        .system-settings-modal {
            max-width: 800px;
            height: auto;
        }

        .settings-tabs {
            display: flex;
            gap: 1rem;
            margin-bottom: 1.5rem;
            border-bottom: 2px solid var(--border-color);
            padding-bottom: 0.5rem;
        }

        .settings-tab {
            padding: 0.5rem 1rem;
            cursor: pointer;
            border-radius: 0.25rem;
            transition: all 0.2s;
        }

        .settings-tab.active {
            background-color: var(--primary-color);
            color: white;
        }

        .settings-tab:hover:not(.active) {
            background-color: var(--background-color);
        }

        .settings-content {
            display: none;
        }

        .settings-content.active {
            display: block;
        }

        .settings-group {
            margin-bottom: 1.5rem;
        }

        .settings-group h3 {
            margin-bottom: 1rem;
            color: var(--text-primary);
        }

        .settings-row {
            display: flex;
            gap: 1rem;
            margin-bottom: 1rem;
        }

        .settings-col {
            flex: 1;
        }

        .settings-label {
            display: block;
            margin-bottom: 0.5rem;
            color: var(--text-secondary);
        }

        .settings-input {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid var(--border-color);
            border-radius: 0.5rem;
            background-color: var(--card-background);
            transition: border-color 0.2s;
        }

        .settings-input:focus {
            outline: none;
            border-color: var(--primary-color);
        }

        .settings-actions {
            display: flex;
            justify-content: flex-end;
            gap: 1rem;
            margin-top: 2rem;
            padding-top: 1rem;
            border-top: 2px solid var(--border-color);
        }

        .markdown-content {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            line-height: 1.6;
            color: var(--text-primary);
            padding: 1rem;
        }

        .markdown-content h1,
        .markdown-content h2,
        .markdown-content h3,
        .markdown-content h4,
        .markdown-content h5,
        .markdown-content h6 {
            margin-top: 1.5em;
            margin-bottom: 0.5em;
            font-weight: 600;
            line-height: 1.25;
        }

        .markdown-content h1 { font-size: 2em; }
        .markdown-content h2 { font-size: 1.5em; }
        .markdown-content h3 { font-size: 1.25em; }
        .markdown-content h4 { font-size: 1em; }
        .markdown-content h5 { font-size: 0.875em; }
        .markdown-content h6 { font-size: 0.75em; }

        .markdown-content p {
            margin-bottom: 1em;
        }

        .markdown-content ul,
        .markdown-content ol {
            margin: 1em 0;
            padding-left: 2em;
        }

        .markdown-content li {
            margin: 0.5em 0;
        }

        .markdown-content code {
            font-family: 'Consolas', 'Monaco', monospace;
            background-color: var(--background-color);
            padding: 0.2em 0.4em;
            border-radius: 3px;
            font-size: 0.9em;
        }

        .markdown-content pre {
            background-color: var(--background-color);
            padding: 1em;
            border-radius: 5px;
            overflow-x: auto;
            margin: 1em 0;
        }

        .markdown-content pre code {
            background-color: transparent;
            padding: 0;
            font-size: 0.9em;
            color: var(--text-primary);
        }

        .markdown-content blockquote {
            border-left: 4px solid var(--border-color);
            margin: 1em 0;
            padding: 0.5em 1em;
            color: var(--text-secondary);
        }

        .markdown-content table {
            border-collapse: collapse;
            width: 100%;
            margin: 1em 0;
        }

        .markdown-content th,
        .markdown-content td {
            border: 1px solid var(--border-color);
            padding: 0.5em;
            text-align: left;
        }

        .markdown-content th {
            background-color: var(--background-color);
            font-weight: 600;
        }

        .markdown-content img {
            max-width: 100%;
            height: auto;
            margin: 1em 0;
            border-radius: 5px;
        }

        .markdown-content a {
            color: var(--primary-color);
            text-decoration: none;
        }

        .markdown-content a:hover {
            text-decoration: underline;
        }

        .markdown-content hr {
            border: none;
            border-top: 2px solid var(--border-color);
            margin: 2em 0;
        }

        /* 修改预览模态框样式 */
        .modal-content {
            max-height: 90vh;
            overflow-y: auto;
        }

        .modal-body {
            padding: 2rem;
        }

        .pdf-viewer {
            width: 100%;
            height: 80vh;
            border: none;
        }

        /* 终端风格预览样式 */
        .terminal-preview {
            background-color: #1e1e1e;
            color: #d4d4d4;
            font-family: 'Consolas', 'Monaco', monospace;
            padding: 1.5rem;
            border-radius: 8px;
            min-height: 400px;
            position: relative;
        }

        .terminal-preview .markdown-content {
            color: #d4d4d4;
        }

        .terminal-preview .markdown-content h1,
        .terminal-preview .markdown-content h2,
        .terminal-preview .markdown-content h3,
        .terminal-preview .markdown-content h4,
        .terminal-preview .markdown-content h5,
        .terminal-preview .markdown-content h6 {
            color: #569cd6;
            border-bottom: 1px solid #404040;
            padding-bottom: 0.5rem;
        }

        .terminal-preview .markdown-content code {
            background-color: #2d2d2d;
            color: #dcdcaa;
            padding: 0.2em 0.4em;
            border-radius: 3px;
        }

        .terminal-preview .markdown-content pre {
            background-color: #2d2d2d;
            border: 1px solid #404040;
        }

        .terminal-preview .markdown-content pre code {
            background-color: transparent;
            color: #dcdcaa;
        }

        .terminal-preview .markdown-content blockquote {
            border-left: 4px solid #404040;
            color: #6a9955;
        }

        .terminal-preview .markdown-content a {
            color: #569cd6;
        }

        .terminal-preview .markdown-content a:hover {
            color: #4ec9b0;
        }

        .terminal-preview .markdown-content table {
            border-color: #404040;
        }

        .terminal-preview .markdown-content th {
            background-color: #2d2d2d;
        }

        .terminal-preview .markdown-content td {
            border-color: #404040;
        }

        .terminal-preview .markdown-content hr {
            border-color: #404040;
        }

        .terminal-preview .markdown-content strong {
            color: #ce9178;
        }

        .terminal-preview .markdown-content em {
            color: #9cdcfe;
        }

        .terminal-preview .markdown-content ul li::before {
            color: #6a9955;
        }

        .terminal-preview .markdown-content ol li::before {
            color: #6a9955;
        }

        .terminal-actions {
            position: absolute;
            top: 1rem;
            right: 1rem;
            display: flex;
            gap: 0.5rem;
            z-index: 10;
        }

        .terminal-button {
            background-color: #2d2d2d;
            color: #d4d4d4;
            border: 1px solid #404040;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.875rem;
            transition: all 0.2s;
        }

        .terminal-button:hover {
            background-color: #404040;
            color: #ffffff;
        }

        .terminal-button.active {
            background-color: #569cd6;
            color: #ffffff;
            border-color: #569cd6;
        }

        .terminal-preview.editable .markdown-content {
            outline: none;
            padding: 1rem;
            border: 1px solid #404040;
            border-radius: 4px;
            min-height: 300px;
        }

        .terminal-preview.editable .markdown-content:focus {
            border-color: #569cd6;
        }

        /* CodeMirror 编辑器样式 */
        .CodeMirror {
            height: 100%;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 14px;
            line-height: 1.6;
            background-color: #1e1e1e !important;
            color: #d4d4d4 !important;
        }

        .CodeMirror-gutters {
            background-color: #1e1e1e !important;
            border-right: 1px solid #404040 !important;
        }

        .CodeMirror-linenumber {
            color: #858585 !important;
        }

        .CodeMirror-cursor {
            border-left: 2px solid #569cd6 !important;
        }

        .CodeMirror-selected {
            background-color: #264f78 !important;
        }

        .CodeMirror-focused .CodeMirror-selected {
            background-color: #264f78 !important;
        }

        .CodeMirror-line::selection,
        .CodeMirror-line > span::selection,
        .CodeMirror-line > span > span::selection {
            background-color: #264f78 !important;
        }

        .editor-container {
            height: calc(100% - 50px);
            position: relative;
        }

        .split-view {
            display: flex;
            height: 100%;
            gap: 1rem;
        }

        .split-view > div {
            flex: 1;
            overflow: auto;
        }

        .split-view .preview {
            padding: 1rem;
            background-color: #1e1e1e;
            border-radius: 4px;
        }

        #customAlert.modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(0,0,0,0.35);
            z-index: 2000;
            align-items: center;
            justify-content: center;
            animation: fadeInBg 0.2s;
        }
        #customAlert .modal-content {
            max-width: 400px;
            margin: auto;
            background: #fff;
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.18);
            padding: 2rem 1.5rem 1.5rem 1.5rem;
            text-align: center;
            animation: popIn 0.25s cubic-bezier(.68,-0.55,.27,1.55);
            position: relative;
        }
        #customAlert .modal-header {
            border-bottom: none;
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        #customAlert .modal-header h2 {
            font-size: 1.25rem;
            color: #2563eb;
            margin: 0;
            flex: 1;
            text-align: left;
        }
        #customAlert .close {
            font-size: 1.5rem;
            color: #64748b;
            cursor: pointer;
            margin-left: 1rem;
            transition: color 0.2s;
        }
        #customAlert .close:hover {
            color: #ef4444;
        }
        #customAlert .modal-body {
            font-size: 1.05rem;
            color: #1e293b;
            margin-top: 0.5rem;
        }
        #customAlert .button.button-primary {
            margin-top: 1.5rem;
            padding: 0.75rem 2.5rem;
            font-size: 1.1rem;
            border-radius: 8px;
            font-weight: 600;
            background: linear-gradient(90deg, #2563eb 0%, #1d4ed8 100%);
            box-shadow: 0 2px 8px rgba(37,99,235,0.08);
        }
        #customAlert .button.button-primary:hover {
            background: linear-gradient(90deg, #1d4ed8 0%, #2563eb 100%);
        }
        @keyframes fadeInBg {
            from { background: rgba(0,0,0,0); }
            to { background: rgba(0,0,0,0.35); }
        }
        @keyframes popIn {
            0% { transform: scale(0.8); opacity: 0; }
            100% { transform: scale(1); opacity: 1; }
        }
    </style>
    <!-- 添加 CodeMirror 相关资源 -->
    <link rel="stylesheet" href="/static/css/codemirror.min.css">
    <link rel="stylesheet" href="/static/css/monokai.min.css">
    <script src="/static/js/codemirror.min.js"></script>
    <script src="/static/js/markdown.min.js"></script>
    <script src="/static/js/continuelist.min.js"></script>
    <script src="/static/js/overlay.min.js"></script>
    <script src="/static/js/active-line.min.js"></script>
    <script src="/static/js/placeholder.min.js"></script>
    <!-- 添加 marked.js 库 -->
    <script src="/static/js/marked.min.js"></script>
    <!-- 引入 SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.10.7/dist/sweetalert2.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.10.7/dist/sweetalert2.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>文档智能系统 Doc2QG</h1>
            <p>Doc2QG: Document to Q&A Knowledge Graph Generation</p>
            <p>专注于将文档转换为 LLM Ready 的结构化数据格式，助力知识管理与应用。</p>
            <div class="header-features">
                <div class="feature-item">
                <div class="feature-icon">📚</div>
                    <span class="feature-text">多格式解析准确率99%</span>
                </div>
                <div class="feature-item">
                    <div class="feature-icon">✏️</div>
                    <span class="feature-text">Markdown二次编辑</span>
                </div>
                <div class="feature-item">
                    <div class="feature-icon">📊</div>
                    <span class="feature-text">OCR识别图片表格</span>
                </div>
                <div class="feature-item">
                    <div class="feature-icon">📤</div>
                    <span class="feature-text">智能提取Q&A</span>
                </div>
                <div class="feature-item">
                    <div class="feature-icon">🕸️</div>
                    <span class="feature-text">智能构建知识图谱</span>
                </div>
                <div class="feature-item">
                    <div class="feature-icon">🌐</div>
                    <span class="feature-text">支持Dify、Ragflow等平台</span>
                </div>
            </div>
        </div>

        <div class="main-container">
            <div class="left-panel">
                <div class="section">
                    <h2>文档转换</h2>
                    <div class="file-upload">
                        <div class="file-input-container" id="dropZone">
                            <input type="file" id="pdfFile" accept=".pdf" class="file-input">
                            <div class="upload-icon">📄</div>
                            <div class="upload-text">
                                <h3>拖放文件到这里</h3>
                                <p>或者点击选择文件</p>
                            </div>
                        </div>
                        <div class="file-info" id="fileInfo">
                            <div class="file-icon">📄</div>
                            <div class="file-details">
                                <div class="file-name" id="selectedFileName"></div>
                                <div class="file-size" id="selectedFileSize"></div>
                            </div>
                            <div class="file-remove" onclick="removeSelectedFile()">✕</div>
                        </div>
                        <div class="upload-actions">
                            <button class="button button-primary" onclick="convertDocument()" id="convertButton">转换文档</button>
                        </div>
                    </div>
                    <div id="convertStatus" class="status-container">
                        <div class="status">> Make Document</div>
                        <button class="status-toggle">▼</button>
                    </div>
                </div>

                <div class="section">
                    <h2>文件列表</h2>
                    <div id="fileList" class="file-list"></div>
                </div>
            </div>

            <div id="qaPanel" class="right-panel">
                <div class="panel-header">
                    <h3>QA 处理</h3>
                    <h4><span id="currentFileName" class="current-file-name"></span> </h4>
                    <div class="panel-actions">
                        <div class="panel-close" onclick="hideQAPanel()"></div>
                    </div>
                </div>
                <div class="prompt-section">
                    <h3>提取规则</h3>
                    <textarea id="promptText" class="prompt-textarea" placeholder="请输入提取规则，例如：
                                1. 提取所有与本文相关的问题
                                2. 确保问题清晰明确
                                3. 答案要完整准确
                                4. 保持专业术语
                                5. 提取数量为10个">1. 提取所有与本文相关的问题
2. 确保问题清晰明确
3. 答案要完整准确
4. 保持专业术语
5. 提取数量为10个
                    </textarea>
                    <div class="extraction-controls">
                        <button id="extractButton" class="button button-primary" onclick="startExtraction()">开始提取</button>
                        <div class="progress-container" style="display: none;">
                            <div class="progress-bar">
                                <div class="progress-fill"></div>
                            </div>
                            <div class="progress-status">正在提取...</div>
                        </div>
                        <div id="qaStatus" class="status-messages"></div>
                    </div>
                </div>

                <div class="qa-preview-section">
                    <div class="qa-preview-header">
                        <span class="qa-preview-title">QA 预览</span>
                        <div class="file-actions">
                            <button class="button button-primary" onclick="sendToKnowledgeBase()">发送到知识库</button>
                            <button class="button button-primary" onclick="exportQA()">导出Q&A</button>
                        </div>
                        <span class="qa-preview-count" id="qaCount"></span>
                    </div>
                    <div id="qaPreviewList" class="qa-list"></div>
            </div>
            </div>
        </div>

        <footer class="footer">
            <div class="footer-content">
                <p>Created by Evan</a> |
                   <a href="https://gitee.com/xujingbao/doc2-qg" target="_blank" class="author-link">Doc2QG</a>
                </p>
            </div>
        </footer>
    </div>

    <!-- QA 预览模态框 -->
    <div id="qaPreviewModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>QA 预览</h2>
                <span class="close" onclick="closeQAPreview()">&times;</span>
            </div>
            <div class="modal-body">
                <div id="qaPreviewList" class="qa-list"></div>
                
                <div class="file-actions" style="margin-top: 1rem;">
                    <button class="button button-success" onclick="sendToKnowledgeBase()">发送到知识库</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 文件预览模态框 -->
    <div id="filePreviewModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="previewTitle"></h2>
                <span class="close" onclick="closeFilePreview()">&times;</span>
            </div>
            <div class="modal-body" id="previewBody"></div>
        </div>
    </div>

    <!-- 添加悬浮设置按钮 -->
    <div class="floating-settings" onclick="showSystemSettings()">
        <span class="text">系统设置</span>
    </div>

    <!-- 系统设置模态框 -->
    <div id="systemSettingsModal" class="modal">
        <div class="modal-content system-settings-modal">
            <div class="modal-header">
                <h2>系统设置</h2>
                <span class="close" onclick="closeSystemSettings()">&times;</span>
            </div>
            <div class="modal-body">
                <div class="settings-tabs">
                    <div class="settings-tab active" onclick="switchSettingsTab('conversion')">转换设置</div>
                    <div class="settings-tab" onclick="switchSettingsTab('knowledge')">知识库设置</div>
                    <div class="settings-tab" onclick="switchSettingsTab('openai')">OpenAI设置</div>
                    <div class="settings-tab" onclick="switchSettingsTab('interface')">界面设置</div>
                    <div class="settings-tab" onclick="switchSettingsTab('system')">系统配置</div>
                </div>

                <!-- 转换设置 -->
                <div id="conversionSettings" class="settings-content active">
                    <div class="settings-group">
                        <h3>PDF转换设置</h3>
                        <div class="settings-row">
                            <div class="settings-col">
                                <label class="settings-label">输出格式</label>
                                <select class="settings-input" id="outputFormat">
                                    <option value="markdown">Markdown</option>
                                    <option value="html">HTML</option>
                                    <option value="json">JSON</option>
                                </select>
                            </div>
                            <div class="settings-col">
                                <label class="settings-label">图片质量</label>
                                <select class="settings-input" id="imageQuality">
                                    <option value="high">高质量</option>
                                    <option value="medium">中等质量</option>
                                    <option value="low">低质量</option>
                                </select>
                            </div>
                        </div>
                        <div class="settings-row">
                            <div class="settings-col">
                                <label class="settings-label">OCR语言</label>
                                <select class="settings-input" id="ocrLanguage">
                                    <option value="chi_sim">简体中文</option>
                                    <option value="eng">英文</option>
                                    <option value="jpn">日文</option>
                                    <option value="kor">韩文</option>
                                </select>
                            </div>
                            <div class="settings-col">
                                <label class="settings-label">并发处理数</label>
                                <input type="number" class="settings-input" id="concurrentProcesses" min="1" max="10" value="3">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 知识库设置 -->
                <div id="knowledgeSettings" class="settings-content">
                    <div class="settings-group">
                        <h3>API配置</h3>
                        <div class="settings-row">
                            <div class="settings-col">
                                <label class="settings-label">Base URL</label>
                                <input type="text" id="systemBaseUrl" class="settings-input" value="">
                            </div>
                            <div class="settings-col">
                                <label class="settings-label">API Key</label>
                                <input type="text" id="systemApiKey" class="settings-input" value="">
                            </div>
                        </div>
                        <div class="settings-row">
                            <div class="settings-col">
                                <label class="settings-label">Dataset ID</label>
                                <input type="text" id="systemDatasetId" class="settings-input" value="">
                            </div>
                            <div class="settings-col">
                                <label class="settings-label">Document ID</label>
                                <input type="text" id="systemDocumentId" class="settings-input" value="">
                            </div>
                        </div>
                    </div>
                    <div class="settings-group">
                        <h3>知识库选项</h3>
                        <div class="settings-row">
                            <div class="settings-col">
                                <label class="settings-label">向量维度</label>
                                <input type="number" class="settings-input" id="vectorDimension" min="128" max="1536" value="1536">
                            </div>
                            <div class="settings-col">
                                <label class="settings-label">相似度阈值</label>
                                <input type="number" class="settings-input" id="similarityThreshold" min="0" max="1" step="0.1" value="0.8">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- OpenAI设置 -->
                <div id="openaiSettings" class="settings-content">
                    <div class="settings-group">
                        <h3>OpenAI API配置</h3>
                        <div class="settings-row">
                            <div class="settings-col">
                                <label class="settings-label">API Key</label>
                                <input type="text" id="openaiApiKey" class="settings-input" value="">
                            </div>
                            <div class="settings-col">
                                <label class="settings-label">API Base URL</label>
                                <input type="text" id="openaiApiBase" class="settings-input" value="">
                            </div>
                        </div>
                        <div class="settings-row">
                            <div class="settings-col">
                                <label class="settings-label">模型</label>
                                <input type="text" id="openaiModel" class="settings-input" placeholder="如 gpt-4o, gpt-3.5-turbo, qwen-turbo 等" value="">
                            </div>
                            <div class="settings-col">
                                <label class="settings-label">Temperature</label>
                                <input type="number" class="settings-input" id="openaiTemperature" min="0" max="2" step="0.1" value="0.7">
                            </div>
                        </div>
                        <div class="settings-row">
                            <div class="settings-col">
                                <label class="settings-label">最大Token数</label>
                                <input type="number" class="settings-input" id="openaiMaxTokens" min="1" max="4000" value="2000">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 界面设置 -->
                <div id="interfaceSettings" class="settings-content">
                    <div class="settings-group">
                        <h3>显示设置</h3>
                        <div class="settings-row">
                            <div class="settings-col">
                                <label class="settings-label">主题</label>
                                <select class="settings-input" id="theme">
                                    <option value="light">浅色</option>
                                    <option value="dark">深色</option>
                                    <option value="system">跟随系统</option>
                                </select>
                            </div>
                            <div class="settings-col">
                                <label class="settings-label">字体大小</label>
                                <select class="settings-input" id="fontSize">
                                    <option value="small">小</option>
                                    <option value="medium" selected>中</option>
                                    <option value="large">大</option>
                                </select>
                            </div>
                        </div>
                        <div class="settings-row">
                            <div class="settings-col">
                                <label class="settings-label">语言</label>
                                <select class="settings-input" id="language">
                                    <option value="zh">简体中文</option>
                                    <option value="en">English</option>
                                </select>
                            </div>
                            <div class="settings-col">
                                <label class="settings-label">动画效果</label>
                                <select class="settings-input" id="animations">
                                    <option value="enabled" selected>启用</option>
                                    <option value="disabled">禁用</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 系统配置 -->
                <div id="systemSettings" class="settings-content">
                    <div class="settings-group">
                        <h3>系统选项</h3>
                        <div class="settings-row">
                            <div class="settings-col">
                                <label class="settings-label">自动保存</label>
                                <select class="settings-input" id="autoSave">
                                    <option value="enabled" selected>启用</option>
                                    <option value="disabled">禁用</option>
                                </select>
                            </div>
                            <div class="settings-col">
                                <label class="settings-label">自动保存间隔（分钟）</label>
                                <input type="number" class="settings-input" id="autoSaveInterval" min="1" max="60" value="5">
                            </div>
                        </div>
                        <div class="settings-row">
                            <div class="settings-col">
                                <label class="settings-label">最大文件大小（MB）</label>
                                <input type="number" class="settings-input" id="maxFileSize" min="1" max="100" value="50">
                            </div>
                            <div class="settings-col">
                                <label class="settings-label">临时文件保留天数</label>
                                <input type="number" class="settings-input" id="tempFileRetention" min="1" max="30" value="7">
                            </div>
                        </div>
                    </div>
                    <div class="settings-group">
                        <h3>日志设置</h3>
                        <div class="settings-row">
                            <div class="settings-col">
                                <label class="settings-label">日志级别</label>
                                <select class="settings-input" id="logLevel">
                                    <option value="debug">调试</option>
                                    <option value="info" selected>信息</option>
                                    <option value="warning">警告</option>
                                    <option value="error">错误</option>
                                </select>
                            </div>
                            <div class="settings-col">
                                <label class="settings-label">日志保留天数</label>
                                <input type="number" class="settings-input" id="logRetention" min="1" max="90" value="30">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="settings-actions">
                    <button class="button button-secondary" onclick="closeSystemSettings()">取消</button>
                    <button class="button button-primary" onclick="saveSystemSettings()">保存设置</button>
                </div>
            </div>
        </div>
    </div>

    <script>

        document.addEventListener('DOMContentLoaded', function() {
            debugLog('页面加载完成');
            // 加载配置
            loadSystemSettings();
        });

        let currentQAList = [];
        let currentFile = null;
        let currentFileContent = '';

        async function convertDocument() {
            const fileInput = document.getElementById('pdfFile');
            const file = fileInput.files[0];
            const convertButton = document.querySelector('.button-primary');
            
            if (!file) {
                showCustomAlert('请选择文件，PDF, image, PPTX, DOCX, XLSX, HTML, EPUB 等类型');
                return;
            }

            // 禁用按钮
            convertButton.disabled = true;
            convertButton.style.opacity = '0.7';
            convertButton.style.cursor = 'not-allowed';

            const formData = new FormData();
            formData.append('file', file);

            // 初始化状态显示区域
            const statusElement = document.getElementById('convertStatus');
            statusElement.innerHTML = '<div class="status">> 开始转换文件...</div>';
            
            // 添加展开/收起按钮
            if (!document.querySelector('.status-toggle')) {
                const statusContainer = statusElement.parentElement;
                statusContainer.classList.add('status-container');
                const toggleButton = document.createElement('button');
                toggleButton.className = 'status-toggle';
                toggleButton.textContent = '▼';
                toggleButton.onclick = function() {
                    statusElement.classList.toggle('expanded');
                    this.textContent = statusElement.classList.contains('expanded') ? '▲' : '▼';
                };
                statusContainer.appendChild(toggleButton);
            }

            try {
                const response = await fetch('/convert', {
                    method: 'POST',
                    body: formData
                });

                const reader = response.body.getReader();
                const decoder = new TextDecoder();

                while (true) {
                    const {value, done} = await reader.read();
                    if (done) break;
                    
                    const text = decoder.decode(value);
                    const lines = text.split('\n');
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(line.slice(6));
                                if (data.message) {
                                    statusElement.innerHTML += `<div class="status">> ${data.message}</div>`;
                                    // 每追加一行，增加两行的高度，并额外增加一些空间
                                    const currentHeight = parseInt(getComputedStyle(statusElement).maxHeight);
                                    statusElement.style.maxHeight = (currentHeight + 48 + 16) + 'px';  // 额外增加16px的空间
                                }
                                if (data.success) {
                                    // 转换成功后立即刷新文件列表
                                    await refreshFileList();
                                    statusElement.innerHTML += `<div class="status success">> 文件列表已更新</div>`;
                                }
                            } catch (e) {
                                console.error('解析消息失败:', e);
                                statusElement.innerHTML += `<div class="status error">> 解析消息失败: ${e.message}</div>`;
                            }
                        }
                    }
                }
            } catch (error) {
                console.error('转换失败: ' + error.message);
                statusElement.innerHTML += `<div class="status error">> 转换失败: ${error.message}</div>`;
            } finally {
                // 恢复按钮状态
                convertButton.disabled = false;
                convertButton.style.opacity = '1';
                convertButton.style.cursor = 'pointer';
            }
        }

        function showQAPreview(qaList) {
            currentQAList = qaList;
            const previewList = document.getElementById('qaPreviewList');
            
            if (!qaList || qaList.length === 0) {
                previewList.innerHTML = '<div class="qa-item">没有提取到 QA 对</div>';
                return;
            }
            
            // 配置 marked 选项
            marked.setOptions({
                breaks: true,  // 支持 GitHub 风格的换行
                gfm: true,     // 启用 GitHub 风格的 Markdown
                headerIds: false, // 禁用标题 ID
                mangle: false,    // 禁用标题 ID 混淆
                sanitize: false   // 允许 HTML 标签
            });
            
            // 创建预览容器
            previewList.innerHTML = `
                <div class="qa-preview-container">
                    <div class="qa-preview-content">
                        <div class="qa-content markdown-content">${marked.parse(qaList[0].answer)}</div>
                    </div>
                    <div class="qa-preview-expand">
                        <button onclick="toggleQAPreview()" class="expand-button">
                            <span class="expand-icon">▼</span>
                            <span class="expand-text">展开</span>
                        </button>
                    </div>
                </div>
            `;
            
            updateQACount(qaList.length);
        }

        function closeQAPreview() {
            const qaPanel = document.getElementById('qaPanel');
            if (qaPanel) {
                qaPanel.style.display = 'none';
            }
            // 清除当前文件状态
            currentFile = null;
            currentFileContent = '';
        }

        function processMarkdownContent(content) {
            // 配置 marked 选项
            marked.setOptions({
                breaks: true,  // 支持 GitHub 风格的换行
                gfm: true,     // 启用 GitHub 风格的 Markdown
                headerIds: false, // 禁用标题 ID
                mangle: false,    // 禁用标题 ID 混淆
                sanitize: false   // 允许 HTML 标签
            });
            return marked.parse(content);
        }

        async function startExtraction() {
            
            if (!currentFile) {
                console.error('请先选择文件');
                return;
            }

            if (!currentFileContent) {
                console.error('文件内容加载失败');
                return;
            }

            const promptText = document.getElementById('promptText').value;
            const extractButton = document.getElementById('extractButton');
            const progressContainer = document.querySelector('.progress-container');
            const progressFill = document.querySelector('.progress-fill');
            const progressStatus = document.querySelector('.progress-status');
            const previewList = document.getElementById('qaPreviewList');

            // 重置状态
            if (previewList) {
                previewList.innerHTML = '<div class="qa-item"><div class="qa-content markdown-content"></div></div>';
            }
            progressContainer.style.display = 'block';
            progressFill.style.width = '0%';
            progressFill.classList.add('animate');
            progressStatus.textContent = `正在提取文件: ${currentFile}...`;
            extractButton.disabled = true;

            try {
                const response = await fetch('/extract_qa', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        content: currentFileContent,
                        prompt: promptText,
                        filename: currentFile
                    })
                });

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                let accumulatedContent = '';
                const qaContent = previewList.querySelector('.qa-content');

                while (true) {
                    const {value, done} = await reader.read();
                    if (done) {
                        // 在流结束时检查是否有内容
                        if (accumulatedContent) {
                            const qaList = parseQAText(accumulatedContent);
                            updateQACount(qaList.length);
                            currentQAList = qaList;// 这行确保 currentQAList 被赋值
                            // 进度条显示为 100% 动画停止
                            progressFill.classList.remove('animate');
                            progressFill.style.width = '100%';
                            progressStatus.textContent = '提取完成。';
                        }
                        break;
                    }
                    
                    buffer += decoder.decode(value, {stream: true});
                    const lines = buffer.split('\n');
                    buffer = lines.pop() || '';
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(line.slice(6));
                                
                                if (data.error) {
                                    console.error(data.error);
                                    progressFill.classList.remove('animate');
                                    progressFill.style.width = '0%';
                                    progressStatus.textContent = '提取失败';
                                    throw new Error(data.error);
                                } else if (data.message) {
                                    // 累积内容
                                    accumulatedContent += data.message;
                                    // 使用 marked 处理 Markdown
                                    qaContent.innerHTML = processMarkdownContent(accumulatedContent);
                                    // 自动滚动到底部
                                    previewList.scrollTop = previewList.scrollHeight;
                                    // 更新进度条
                                    progressFill.style.width = '100%';
                                    progressStatus.textContent = '正在生成...';
                                }
                            } catch (e) {
                                console.error('解析消息失败:', e);
                                progressFill.classList.remove('animate');
                                progressFill.style.width = '0%';
                                progressStatus.textContent = '提取失败';
                                extractButton.disabled = false;
                            }
                        }
                    }
                }
                
            } catch (error) {
                console.error('提取失败:', error);
                progressFill.classList.remove('animate');
                progressFill.style.width = '0%';
                progressStatus.textContent = '提取失败';
            } finally {
                extractButton.disabled = false;
            }
        }

        function parseQAText(text) {
            const qaList = [];
            // 修改正则表达式以更准确地匹配 QA 对
            const qaPattern = /Q: (.*?)\nA: (.*?)(?=\nQ:|$)/gs;
            let match;

            while ((match = qaPattern.exec(text)) !== null) {
                qaList.push({
                    question: match[1].trim(),
                    answer: match[2].trim()
                });
            }

            return qaList;
        }

        async function sendToKnowledgeBase() {
            const sendBtn = document.querySelector('.file-actions button[onclick="sendToKnowledgeBase()"]');
            if (sendBtn) {
                sendBtn.disabled = true;
                sendBtn.style.opacity = '0.7';
                sendBtn.style.cursor = 'not-allowed';
            }
            if (!currentQAList || currentQAList.length === 0) {
                showCustomAlert('没有QA数据可发送，请先提取QA。');
                if (sendBtn) {
                    sendBtn.disabled = false;
                    sendBtn.style.opacity = '1';
                    sendBtn.style.cursor = 'pointer';
                }
                return;
            }
            try {
                // 只发送 qa_list，不再发送 api_config
                const sendResponse = await fetch('/send_to_knowledge_base', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        qa_list: currentQAList
                    })
                });
                const result = await sendResponse.json();
                if (result.success) {
                    showCustomAlert('发送成功', '成功');
                } else {
                    showCustomAlert('发送失败: ' + result.message, '失败');
                }
            } catch (error) {
                console.error('发送到知识库失败:', error);
                showCustomAlert('发送到知识库失败: ' + error.message, '失败');
            } finally {
                if (sendBtn) {
                    sendBtn.disabled = false;
                    sendBtn.style.opacity = '1';
                    sendBtn.style.cursor = 'pointer';
                }
            }
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('qaPreviewModal');
            if (event.target == modal) {
                closeQAPreview();
            }
        }

        async function refreshFileList() {
            try {
                const response = await fetch('/list_files');
                const data = await response.json();
                const fileList = document.getElementById('fileList');
                
                if (data.files.length === 0) {
                    fileList.innerHTML = '<div class="file-item">暂无文件</div>';
                } else {
                    fileList.innerHTML = data.files.map(file => `
                        <div class="file-item">
                            <span class="file-name" onclick="previewFile('${file}')">${file}</span>
                            <div class="file-actions">
                                ${file.toLowerCase().endsWith('.md') ? 
                                    `<button class="button button-primary" onclick="processQAFromFile('${file}')">处理 QA</button>` : 
                                    ''}
                                <a href="/download?filename=${encodeURIComponent(file)}" class="button">下载</a>
                            </div>
                        </div>
                    `).join('');
                }
            } catch (error) {
                console.error('获取文件列表失败:', error);
                const fileList = document.getElementById('fileList');
                fileList.innerHTML = '<div class="file-item error">获取文件列表失败</div>';
            }
        }

        function showQAPanel() {
            document.getElementById('qaPanel').classList.add('active');
        }

        function hideQAPanel() {
            document.getElementById('qaPanel').classList.remove('active');
            currentFile = null;
            currentFileContent = '';
            document.getElementById('qaPreviewList').innerHTML = '';
            updateQACount(0);
        }

        async function processQAFromFile(filename) {
            debugLog(`处理文件: ${filename}`);
            try {
                currentFile = filename;
                // 更新当前文件名显示
                document.getElementById('currentFileName').textContent = filename;
                const response = await fetch(`/preview?filename=${encodeURIComponent(filename)}`);
                const data = await response.json();
                
                if (data.type === 'markdown') {
                    showQAPanel();
                    currentFileContent = data.content;
                    debugLog(`文件内容已加载: ${currentFileContent.length} 字符`);
                } else {
                    console.error('只能处理 Markdown 文件');
                }
            } catch (error) {
                console.error('处理文件失败:', error);
            }
        }

        async function previewFile(filename) {
            try {
                const response = await fetch(`/preview?filename=${encodeURIComponent(filename)}`);
                const data = await response.json();
                       
                const modal = document.getElementById('filePreviewModal');
                const title = document.getElementById('previewTitle');
                const body = document.getElementById('previewBody');
                
                title.textContent = filename;
                
                if (data.type === 'markdown') {
                    // 创建终端风格的预览容器，默认以编辑模式打开
                    body.innerHTML = `
                        <div class="terminal-preview">
                            <div class="terminal-actions">
                                <button class="terminal-button" onclick="saveFileContent('${filename}')">保存</button>
                            </div>
                            <div class="editor-container editable"></div>
                        </div>
                    `;

                    // 初始化 CodeMirror 编辑器
                    const container = body.querySelector('.editor-container');
                    
                    // 确保容器有足够的高度
                    container.style.height = '800px';
                    container.style.minHeight = '800px';
                    
                    // 直接创建 CodeMirror 实例
                    editor = CodeMirror(container, {
                        value: data.content,
                        mode: 'markdown',
                        theme: 'monokai',
                        lineNumbers: true,
                        lineWrapping: true,
                        autoCloseBrackets: true,
                        matchBrackets: true,
                        indentUnit: 4,
                        tabSize: 4,
                        indentWithTabs: false,
                        extraKeys: {
                            "Enter": "newlineAndIndentContinueMarkdownList"
                        },
                        viewportMargin: Infinity
                    });

                    // 设置编辑器大小
                    editor.setSize(null, '500px');
                    
                    // 强制刷新编辑器
                    setTimeout(() => {
                        editor.refresh();
                        console.log('编辑器刷新后内容:', editor.getValue());
                    }, 100);
                    
                } else if (data.type === 'pdf') {
                    body.innerHTML = `<iframe class="pdf-viewer" src="${data.url}"></iframe>`;
                } else {
                    body.innerHTML = `<p>此文件类型不支持预览，请下载后查看。</p>`;
                }
                
                modal.style.display = 'block';
            } catch (error) {
                console.error('预览文件失败:', error);
                showCustomAlert('预览文件失败: ' + error.message);
            }
        }

        function closeFilePreview() {
            document.getElementById('filePreviewModal').style.display = 'none';
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('filePreviewModal');
            if (event.target == modal) {
                closeFilePreview();
            }
        }

        function updateQACount(count) {
            document.getElementById('qaCount').textContent = `${count} 个QA对`;
        }

        // 页面加载时刷新文件列表
        document.addEventListener('DOMContentLoaded', refreshFileList);

        function showSystemSettings() {
            document.getElementById('systemSettingsModal').style.display = 'block';
            loadSystemSettings();
        }

        function closeSystemSettings() {
            document.getElementById('systemSettingsModal').style.display = 'none';
        }

        function switchSettingsTab(tabName) {
            // 更新标签页状态
            document.querySelectorAll('.settings-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            document.querySelectorAll('.settings-content').forEach(content => {
                content.classList.remove('active');
            });

            // 激活选中的标签页
            document.querySelector(`.settings-tab[onclick="switchSettingsTab('${tabName}')"]`).classList.add('active');
            document.getElementById(`${tabName}Settings`).classList.add('active');
        }

        async function loadSystemSettings() {
            try {
                const response = await fetch('/api/config');
                const data = await response.json();
                
                // 解析 properties 格式的配置
                const settings = {
                    api: {},
                    openai: {},
                    settings: {}
                };
                
                if (data.content) {
                    let currentSection = 'settings';
                    data.content.split('\n').forEach(line => {
                        line = line.trim();
                        if (!line || line.startsWith('#')) return; // 跳过空行和注释
                        
                        if (line.startsWith('[') && line.endsWith(']')) {
                            currentSection = line.slice(1, -1).toLowerCase();
                            return;
                        }
                        
                        let key, value;
                        if (currentSection === 'api' || currentSection === 'openai') {
                            // API 和 OpenAI 部分使用 "key = value" 格式
                            const parts = line.split(' = ');
                            if (parts.length === 2) {
                                key = parts[0].trim();
                                value = parts[1].trim();
                            }
                        } else {
                            // Settings 部分使用 "key=value" 格式
                            const equalIndex = line.indexOf('=');
                            if (equalIndex > 0) {
                                key = line.substring(0, equalIndex).trim();
                                value = line.substring(equalIndex + 1).trim();
                            }
                        }
                        
                        if (key && value) {
                            if (currentSection === 'api') {
                                settings.api[key] = value;
                            } else if (currentSection === 'openai') {
                                settings.openai[key] = value;
                            } else {
                                settings.settings[key] = value;
                            }
                        }
                    });
                }
                
                // 加载知识库设置 (API 部分)
                document.getElementById('systemBaseUrl').value = settings.api.base_url || '';
                document.getElementById('systemApiKey').value = settings.api.api_key || '';
                document.getElementById('systemDatasetId').value = settings.api.dataset_id || '';
                document.getElementById('systemDocumentId').value = settings.api.document_id || '';
                
                // 加载 OpenAI 设置                
                // 设置其他 OpenAI 相关值
                document.getElementById('openaiApiKey').value = settings.openai.api_key || '';
                document.getElementById('openaiApiBase').value = settings.openai.api_base || '';
                document.getElementById('openaiTemperature').value = settings.openai.temperature || '';
                document.getElementById('openaiMaxTokens').value = settings.openai.max_tokens || '';
                document.getElementById('openaiModel').value = settings.openai.model || '';

                // 设置默认的转换设置
                document.getElementById('outputFormat').value = settings.settings.output_format || 'markdown';
                document.getElementById('imageQuality').value = settings.settings.image_quality || 'medium';
                document.getElementById('ocrLanguage').value = settings.settings.ocr_language || 'chi_sim';
                document.getElementById('concurrentProcesses').value = settings.settings.concurrent_processes || 3;

                // 设置默认的知识库选项
                document.getElementById('vectorDimension').value = settings.settings.vector_dimension || 1536;
                document.getElementById('similarityThreshold').value = settings.settings.similarity_threshold || 0.8;

                // 设置默认的界面设置
                document.getElementById('theme').value = settings.settings.theme || 'light';
                document.getElementById('fontSize').value = settings.settings.font_size || 'medium';
                document.getElementById('language').value = settings.settings.language || 'zh';
                document.getElementById('animations').value = settings.settings.animations || 'enabled';

                // 设置默认的系统配置
                document.getElementById('autoSave').value = settings.settings.auto_save || 'enabled';
                document.getElementById('autoSaveInterval').value = settings.settings.auto_save_interval || 5;
                document.getElementById('maxFileSize').value = settings.settings.max_file_size || 50;
                document.getElementById('tempFileRetention').value = settings.settings.temp_file_retention || 7;
                document.getElementById('logLevel').value = settings.settings.log_level || 'info';
                document.getElementById('logRetention').value = settings.settings.log_retention || 30;

                // 应用已保存的设置
                applySettings(settings.settings);
            } catch (error) {
                console.error('加载系统设置失败:', error);
            }
        }

        async function saveSystemSettings() {
            const settings = {
                api: {
                    base_url: document.getElementById('systemBaseUrl').value,
                    api_key: document.getElementById('systemApiKey').value,
                    dataset_id: document.getElementById('systemDatasetId').value,
                    document_id: document.getElementById('systemDocumentId').value
                },
                openai: {
                    api_key: document.getElementById('openaiApiKey').value,
                    api_base: document.getElementById('openaiApiBase').value,
                    model: document.getElementById('openaiModel').value,
                    temperature: document.getElementById('openaiTemperature').value,
                    max_tokens: document.getElementById('openaiMaxTokens').value
                },
                settings: {
                    output_format: document.getElementById('outputFormat').value,
                    image_quality: document.getElementById('imageQuality').value,
                    ocr_language: document.getElementById('ocrLanguage').value,
                    concurrent_processes: parseInt(document.getElementById('concurrentProcesses').value),
                    vector_dimension: parseInt(document.getElementById('vectorDimension').value),
                    similarity_threshold: parseFloat(document.getElementById('similarityThreshold').value),
                    theme: document.getElementById('theme').value,
                    font_size: document.getElementById('fontSize').value,
                    language: document.getElementById('language').value,
                    animations: document.getElementById('animations').value,
                    auto_save: document.getElementById('autoSave').value,
                    auto_save_interval: parseInt(document.getElementById('autoSaveInterval').value),
                    max_file_size: parseInt(document.getElementById('maxFileSize').value),
                    temp_file_retention: parseInt(document.getElementById('tempFileRetention').value),
                    log_level: document.getElementById('logLevel').value,
                    log_retention: parseInt(document.getElementById('logRetention').value)
                }
            };
            
            try {
                // 将设置转换为 properties 格式
                const propertiesContent = [
                    '[API]',
                    ...Object.entries(settings.api).map(([key, value]) => `${key} = ${value}`),
                    '',
                    '[OpenAI]',
                    ...Object.entries(settings.openai).map(([key, value]) => `${key} = ${value}`),
                    '',
                    '[Settings]',
                    ...Object.entries(settings.settings).map(([key, value]) => `${key}=${value}`)
                ].join('\n');


                const response = await fetch('/api/config', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        content: propertiesContent
                    })
                });

                const data = await response.json();
                                if (data.success) {
                    applySettings(settings.settings);
                    closeSystemSettings();
                    alert('系统设置已保存');
                } else {
                    alert('保存设置失败: ' + data.message);
                }
            } catch (error) {
                console.error('保存系统设置失败:', error);
                alert('保存设置失败: ' + error.message);
            }
        }

        function applySettings(settings) {
            // 应用主题
            if (settings.theme === 'dark') {
                document.documentElement.classList.add('dark-theme');
            } else {
                document.documentElement.classList.remove('dark-theme');
            }

            // 应用字体大小
            document.documentElement.style.fontSize = {
                'small': '14px',
                'medium': '16px',
                'large': '18px'
            }[settings.font_size];

            // 应用语言
            document.documentElement.lang = settings.language;

            // 应用动画
            if (settings.animations === 'disabled') {
                document.documentElement.classList.add('no-animations');
            } else {
                document.documentElement.classList.remove('no-animations');
            }
        }

        // 添加调试函数
        function debugLog(message) {
            console.log(`[Debug] ${message}`);
        }

        // 确保 DOM 加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            debugLog('页面加载完成');
            // 绑定按钮点击事件
            const extractButton = document.getElementById('extractButton');
            if (extractButton) {
                extractButton.addEventListener('click', function(e) {
                    e.preventDefault();
                    startExtraction();
                });
            } else {
                console.error('未找到提取按钮');
            }
        });

        // 添加切换预览展开/收起的函数
        function toggleQAPreview() {
            const container = document.querySelector('.qa-preview-container');
            const content = document.querySelector('.qa-preview-content');
            const button = document.querySelector('.expand-button');
            const icon = button.querySelector('.expand-icon');
            const text = button.querySelector('.expand-text');
            
            if (container.classList.contains('expanded')) {
                // 收起
                container.classList.remove('expanded');
                content.style.maxHeight = '100px';
                icon.textContent = '▼';
                text.textContent = '展开';
                        } else {
                // 展开
                container.classList.add('expanded');
                content.style.maxHeight = 'none';
                icon.textContent = '▲';
                text.textContent = '收起';
            }
        }

        let editor = null;

        function toggleEditMode(button) {
            const preview = button.closest('.terminal-preview');
            const container = preview.querySelector('.editor-container');
            const isEditable = container.classList.contains('editable');
            
            if (isEditable) {
                // 切换到预览模式
                container.classList.remove('editable');
                container.innerHTML = `<div class="markdown-content">${processMarkdownContent(editor.getValue())}</div>`;
                editor = null;
                button.textContent = '编辑';
                button.classList.remove('active');
            } else {
                // 切换到编辑模式
                const content = container.querySelector('.markdown-content').innerText;
                container.classList.add('editable');
                container.innerHTML = '';
                
                // 初始化 CodeMirror 编辑器
                editor = CodeMirror(container, {
                    value: content,
                    mode: 'markdown',
                    theme: 'monokai',
                    lineNumbers: true,
                    lineWrapping: true,
                    autoCloseBrackets: true,
                    matchBrackets: true,
                    indentUnit: 4,
                    tabSize: 4,
                    indentWithTabs: false,
                    extraKeys: {
                        "Enter": "newlineAndIndentContinueMarkdownList"
                    },
                    viewportMargin: Infinity
                });

                // 设置编辑器高度
                editor.setSize(null, container.offsetHeight);
                
                button.textContent = '预览';
                button.classList.add('active');
            }
        }

        async function saveFileContent(filename) {
            try {
                const content = editor.getValue();
                
                const response = await fetch('/save_file', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        filename: filename,
                        content: content
                    })
                });

                const result = await response.json();
                if (result.success) {
                    showCustomAlert('文件保存成功', '成功');
                } else {
                    showCustomAlert('保存失败: ' + result.message, '失败');
                }
            } catch (error) {
                console.error('保存文件失败:', error);
                showCustomAlert('保存文件失败: ' + error.message, '失败');
            }
        }

        // 添加文件拖放和选择相关的事件处理
        document.addEventListener('DOMContentLoaded', function() {
            const dropZone = document.getElementById('dropZone');
            const fileInput = document.getElementById('pdfFile');
            const fileInfo = document.getElementById('fileInfo');
            const selectedFileName = document.getElementById('selectedFileName');
            const selectedFileSize = document.getElementById('selectedFileSize');
            const convertButton = document.getElementById('convertButton');

            // 处理文件拖放
            dropZone.addEventListener('dragover', (e) => {
                e.preventDefault();
                dropZone.classList.add('dragover');
            });

            dropZone.addEventListener('dragleave', () => {
                dropZone.classList.remove('dragover');
            });

            dropZone.addEventListener('drop', (e) => {
                e.preventDefault();
                dropZone.classList.remove('dragover');
                const files = e.dataTransfer.files;
                if (files.length > 0) {
                    handleFileSelection(files[0]);
                }
            });

            // 处理文件选择
            fileInput.addEventListener('change', (e) => {
                if (e.target.files.length > 0) {
                    handleFileSelection(e.target.files[0]);
                }
            });

            function handleFileSelection(file) {
                if (file.type === 'application/pdf') {
                    selectedFileName.textContent = file.name;
                    selectedFileSize.textContent = formatFileSize(file.size);
                    fileInfo.classList.add('active');
                    convertButton.disabled = false;
                } else {
                    alert('请选择 PDF 文件');
                    fileInput.value = '';
                }
            }
        });

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        function removeSelectedFile() {
            const fileInput = document.getElementById('pdfFile');
            const fileInfo = document.getElementById('fileInfo');
            const convertButton = document.getElementById('convertButton');
            
            fileInput.value = '';
            fileInfo.classList.remove('active');
            convertButton.disabled = true;
        }

        function exportQA() {
            if (!currentQAList || currentQAList.length === 0) {
                showCustomAlert('没有可导出的QA对，请先提取QA。');
                return;
            }
            let content = '';
            currentQAList.forEach((qa, idx) => {
                content += `Q: ${qa.question}\nA: ${qa.answer}\n\n`;
            });
            const blob = new Blob([content], {type: 'text/plain'});
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'qa_export.txt';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        function showCustomAlert(msg, title) {
            Swal.fire({
                title: title || '提示',
                text: msg,
                confirmButtonText: '确定',
                customClass: {
                    popup: 'swal2-popup',
                    title: 'swal2-title',
                    confirmButton: 'swal2-confirm'
                }
            });
        }

        function closeCustomAlert() {
            document.getElementById('customAlert').style.display = 'none';
        }
    </script>
</body>
</html>

